import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter_oldman_health/api/constant.dart';
import 'package:flutter_oldman_health/api/health_data_service.dart';
import 'package:flutter_oldman_health/chart/flutter_echarts.dart';
import 'package:flutter_oldman_health/models/health_data_model.dart';
import 'package:flutter_oldman_health/models/relation_model.dart';
import 'package:flutter_oldman_health/utils/healthdata_charts_utils.dart';
import 'package:flutter_oldman_health/utils/time_machine_util.dart';

final List listData = ["血氧", "心率", "体温", "计步"];

class HealthRecordChartsPage extends StatefulWidget {
  final int healthRecordType;
  final FamilyRelationItem familyRelationItem;

  HealthRecordChartsPage(
      {Key k, this.familyRelationItem, this.healthRecordType})
      : super(key: k);

  @override
  HealthRecordChartsState createState() {
    return HealthRecordChartsState(healthRecordType);
  }
}

class HealthRecordChartsState extends State<HealthRecordChartsPage> {
  int healthRecordType;
  String unit;
  String unitX = "日";

  String healthRecordTitle;

  List<String> dateList = [];
  List<String> valueList = [];
  List<List<String>> valueList2 = [];

  List<HealthItemData> serialData;
  List<HealthAverageData> averageData;
  bool showLoading = true;
  int dateType = 0;
  int num = 0;
  int startTime = TimeMachineUtil.getTimestampLatest(true, 0);
  int endTime = TimeMachineUtil.getTimestampLatest(false, 0);

  //DateTime.now().add(new Duration(days: 1)).millisecondsSinceEpoch;

  List<String> dateTypeList = ["日", "月", "年"];
  String dateTimeStr = "";
  Size screenSize;
  DateTime selectDateTime = DateTime.now();
  String today = formatDate(DateTime.now(), [yyyy, "年", mm, "月", dd, "日"]);
  HealthDataChartsUtils healthDataChartsUtils = HealthDataChartsUtils();

  HealthRecordChartsState(this.healthRecordType) {
    healthRecordTitle = listData[healthRecordType];
  }

  queryHealthRecordChartData(int healthRecordType) async {
    print("queryHealthRecordChartData");
    var response;
    String memberId = widget.familyRelationItem.memberId;
    switch (healthRecordType) {
      case 0:
        unit = "%";
        response = await HealthDataService.queryBloodOxygen(
            type: dateType,
            memberId: memberId,
            startTime: startTime,
            endTime: endTime);
        break;
      case 1:
        unit = "次/分";
        response = await HealthDataService.queryHeartRate(
            type: dateType,
            memberId: memberId,
            startTime: startTime,
            endTime: endTime);
        break;
      case 2:
        unit = "°C";
        response = await HealthDataService.queryTemperature(
            type: dateType,
            memberId: memberId,
            startTime: startTime,
            endTime: endTime);
        break;
      default:
        unit = "步";
        response = await HealthDataService.queryStepNumber(
            type: dateType,
            memberId: memberId,
            startTime: startTime,
            endTime: endTime);
        break;
    }
    if (null != response && response.statusCode == 200) {
      if (dateType == 0) {
        serialData = HealthListModel.fromJson(response.data).data;
      } else {
        averageData = HealthAverageListModel.fromJson(response.data).data;
      }

      List<List> list;
      if (dateType == 0) {
        list = healthDataChartsUtils.showDayCharts(
            isTemperatureType(), isStepHealthType(), serialData);
        setState(() {
          unitX = "";
          showLoading = false;
          if (list[0].length == 0) {
            serialData = [];
          } else {
            dateList = list[0];
            valueList = list[1];
          }
        });
      } else if (isYearDateType()) {
        unitX = "月";

        list = healthDataChartsUtils.getAverageDataList(
            isTemperatureType(), averageData, unitX);
        setState(() {
          showLoading = false;
          if (list[0].length == 0) {
            averageData = [];
          } else {
            dateList = list[0];
            valueList2 = list[1];
            print(valueList2);
          }
        });
      } else {
        unitX = "日";
        list = healthDataChartsUtils.getAverageDataList2(
            isTemperatureType(), averageData, unitX);
        setState(() {
          showLoading = false;
          if (list[0].length == 0) {
            averageData = [];
          } else {
            dateList = list[0];
            valueList2 = list[1];
            print(valueList2);
          }
        });
      }
    }
  }

  @override
  void initState() {
    super.initState();
    if (isStepHealthType()) {
      Map<String, String> timeMap = TimeMachineUtil.getWeeksDate(0);
      startTime = int.parse(timeMap['monDayStamp']);
      endTime = int.parse(timeMap['sunDayStamp']);
      dateTimeStr = formatDate(DateTime.fromMillisecondsSinceEpoch(startTime),
              [mm, "月", dd, "日"]) +
          " - ${formatDate(DateTime.fromMillisecondsSinceEpoch(endTime), [
                mm,
                "月",
                dd,
                "日"
              ])}";
    } else {
      dateTimeStr = formatDate(DateTime.fromMillisecondsSinceEpoch(startTime),
          [yyyy, "年", mm, "月", dd, "日"]);
    }
    queryHealthRecordChartData(healthRecordType);
  }

  @override
  Widget build(BuildContext context) {
    screenSize = MediaQuery.of(context).size;

    return Scaffold(
        resizeToAvoidBottomInset: true,
        body: WillPopScope(
            onWillPop: () async {
              Navigator.pop(context, true);
              return false;
            },
            child: Container(
                color: Constant.backgroundColor,
                child: Column(children: [
                  _getTitle(healthRecordTitle),
                  // Text(
                  //   "最近$healthRecordTitle记录",
                  //   style: TextStyle(
                  //       fontSize: 19,
                  //       fontWeight: FontWeight.w300,
                  //       color: Color(0xff333333))),
                  Expanded(
                      flex: 1,
                      child: showLoading
                          ? Container(
                              width: double.infinity,
                              padding: EdgeInsets.only(top: 10),
                              alignment: Alignment.center,
                              child: const CircularProgressIndicator())
                          : Column(children: [
                              Wrap(children: getDateTypeListWidgets()),
                              Padding(padding: EdgeInsets.only(top: 8)),
                              Wrap(
                                  crossAxisAlignment: WrapCrossAlignment.center,
                                  children: [
                                    GestureDetector(
                                        onTap: () {
                                          num = num - 1;
                                          refreshDateTime();
                                        },
                                        child: Container(
                                            padding: EdgeInsets.fromLTRB(
                                                22, 8, 18, 8),
                                            child: Icon(Icons.arrow_back_ios,
                                                color: Color(0xff666666)))),
                                    Text(
                                      dateTimeStr,
                                      style: TextStyle(
                                          fontSize: 18,
                                          color: Color(0xff666666)),
                                    ),
                                    GestureDetector(
                                        onTap: () {
                                          num = num + 1;
                                          refreshDateTime();
                                        },
                                        child: Container(
                                            padding: EdgeInsets.fromLTRB(
                                                18, 8, 22, 8),
                                            child: Icon(Icons.arrow_forward_ios,
                                                color: Color(0xff666666))))
                                  ]),
                              _showCharts(),
                              if (!isEmptyDataText())
                                Container(
                                    padding: EdgeInsets.only(left: 40, top: 8),
                                    alignment: Alignment.centerLeft,
                                    child: Text("* 拖动上方进度条放大、缩小图表",
                                        style: TextStyle(fontSize: 14)))
                            ]))
                ]))));
  }

  List<Widget> getDateTypeListWidgets() {
    var dateTypeWidgets = dateTypeList.map((e) => GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          dateType = dateTypeList.indexOf(e);
          num = 0;
          refreshDateTime();
        },
        child: Container(
            decoration: BoxDecoration(
                // color: Color(0xff41BAB0),
                color: (dateTypeList[dateType] == e
                    ? Color(0xff41BAB0)
                    : Colors.transparent),
                border: Border.all(
                    //color: Color(0xff41BAB0)),
                    color: (dateTypeList[dateType] == e
                        ? Color(0xff41BAB0)
                        : Color(0xff999999))),
                borderRadius: BorderRadius.circular(8)),
            padding: EdgeInsets.fromLTRB(24, 8, 24, 8),
            margin: EdgeInsets.fromLTRB(16, 8, 16, 8),
            child: Text(
                isStepHealthType() && dateTypeList.indexOf(e) == 0 ? "周" : e,
                textAlign: TextAlign.center,
                style: TextStyle(
                    fontSize: 18,
                    color: (dateTypeList[dateType] == e
                        ? Color(0xffffffff)
                        : Color(0xff666666)))))));
    return dateTypeWidgets.toList();
  }

  bool isTemperatureType() {
    return healthRecordType == 2;
    // return false;
  }

  bool isStepHealthType() {
    return healthRecordType == 3;
  }

  bool isYearDateType() {
    return dateType == 2;
  }

  bool isEmptyDataText() {
    if (dateType == 0) {
      return (null == serialData || serialData.length == 0);
    } else {
      return (null == averageData || averageData.length == 0);
    }
  }

  Widget _showCharts() {
    print("_showCharts");
    if (isEmptyDataText()) {
      return Container(
          padding: EdgeInsets.only(top: 60),
          child: Text("暂无数据",
              style: TextStyle(
                  fontSize: 28,
                  fontWeight: FontWeight.w300,
                  color: Colors.black54)));
    }
    print("_showCharts ${dateList.length}");

    return Container(
        width: screenSize.width - 20,
        height: screenSize.height - 280,
        padding: EdgeInsets.only(top: 10),
        child: _getBarCharts(healthRecordType, dateList,
            (dateType == 0) ? valueList : valueList2)
        // child: getEasyBarCharts(dateList, valueList) //_getLineCharts
        // child: BarChartWidget(dateType,healthRecordType,dateList, valueList2) //_getLineCharts
        );
  }

  void refreshDateTime() {
    print("dateType:$dateType num:$num");
    if (dateType == 0) {
      if (isStepHealthType()) {
        Map<String, String> timeMap = TimeMachineUtil.getWeeksDate(num);
        startTime = int.parse(timeMap['monDayStamp']);
        endTime = int.parse(timeMap['sunDayStamp']);
        dateTimeStr = formatDate(DateTime.fromMillisecondsSinceEpoch(startTime),
                [mm, "月", dd, "日"]) +
            " - ${formatDate(DateTime.fromMillisecondsSinceEpoch(endTime), [
                  mm,
                  "月",
                  dd,
                  "日"
                ])}";
      } else {
        startTime = TimeMachineUtil.getTimestampLatest(true, num);
        endTime = TimeMachineUtil.getTimestampLatest(false, num);
        dateTimeStr = formatDate(DateTime.fromMillisecondsSinceEpoch(startTime),
            [yyyy, "年", mm, "月", dd, "日"]);
      }
    } else if (dateType == 1) {
      Map<String, String> timeMap = TimeMachineUtil.getMonthDate(num);
      dateTimeStr = "${timeMap['startDate'].toString().substring(0, 4)}年"
          "${timeMap['startDate'].toString().substring(5, 7)}月";
      print(
          "startTime2:${timeMap['startDateStamp']} endTime:${timeMap['endDateStamp']}");

      startTime = int.parse(timeMap['startDateStamp']);
      endTime = int.parse(timeMap['endDateStamp']);
    } else if (dateType == 2) {
      Map timeMap = TimeMachineUtil.getStartEndYearDate(num);
      dateTimeStr = timeMap['startTime'].toString().substring(0, 4) + "年";
      print(
          "startTime3:${timeMap['startStamp']} endTime:${timeMap['endDateStamp']}");

      startTime = timeMap['startStamp'];
      endTime = timeMap['endStamp'];
    }
    print("startTime:$startTime endTime:$endTime");
    print("dateTimeStr 294 $dateTimeStr");

    queryHealthRecordChartData(healthRecordType);
  }

  List titleList = ["'平均'", "'最高'", "'最低'"];
  List titleList2 = ["平均", "最高", "最低"];

  Widget _getBarCharts(int healthType, List<String> dataX, List legendData) {
    String legend = " ";
    // dateType == 0
    //     ? " "
    //     : '''legend: {
    // top: '2%',data: $titleList },''';
    String series2 = " ";
    // dateType == 0
    //     ? " "
    //     : ''',
    //   {
    //   name: '${titleList2[1]}',
    //   type: 'bar',
    //   label: labelOption,
    //   barWidth: '20%',
    //   emphasis: {
    //     focus: 'series'
    //   },
    //   data: ${legendData[1]}
    // },{
    //   name: '${titleList2[2]}',
    //   type: 'bar',
    //   label: labelOption,
    //   barWidth: '20%',
    //   emphasis: {
    //     focus: 'series'
    //   },
    //   data: ${legendData[2]}
    // }''';
    return Echarts(reloadAfterInit: true, extraScript: '''
const labelOption = {
  show: false,
  position: 'insideBottom',
  distance: 15,
  align: 'left',
  verticalAlign: 'middle',
  rotate: 90,
  formatter: '{c}  {name|{a}}',
  fontSize: 14,
  rich: {
    name: {}
  }
};
    ''', option: '''
    {
    grid: {
        left: '3%',
        right: '5%',
        bottom: '0%',
        top: '7%',
        height: '78%',
        containLabel: true,
        z: 12,
      },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },  
  dataZoom:[{type:'inside',
          left:'10%',
          right:'12%',},
           {type:'slider',
          left:'10%',
          right:'12%',},
            { 
              start: 0,
              end: 10,
              
          left:'10%',
          right:'12%',
              handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
              handleSize: '60%',
              handleStyle: {
                  color: '#fff',
                  shadowBlur: 6,
                  shadowColor: 'rgba(0, 0, 0, 0.6)',
                  shadowOffsetX: 2,
                  shadowOffsetY: 2
              }
          }],
 $legend
   // legend: { 
   //      top: '2%',data: titleList },
  toolbox: {
    show: true,
    orient: 'vertical',
    left: 'right',
    top: 'center',
    feature: {
      mark: { show: true },
      // dataView: { show: true, readOnly: false },
      //magicType: { show: true, type: ['line', 'bar', 'stack'] },
      //restore: { show: true },
      //saveAsImage: { show: true }
    }
  },
  xAxis: [
    {
      type: 'category',
      axisTick: { show: false },
      data: $dataX,
      axisLabel: ${(dateType == 0 && healthRecordType != 3) ? "{ show:false}" : "{ show:true}"}
    }
  ],
  yAxis: [
    { 
      name:'${listData[healthType]} $unit',
      type: 'value'

      // axisLabel:{ formatter:'{value}$unit'}
    }
  ],
  series: [
    {
      name: '${dateType == 0 ? listData[healthType] : (healthRecordType == 3 && dateType == 1 ? "" : titleList2[0]) + listData[healthType]}',
      type: 'bar',
      barGap: 0,
      label: labelOption,
      //label: {show:true,position: 'top',formatter: '{c} $unit'},
      barWidth:'${legendData.length > 5 ? 60 : 20}%',
      emphasis: {
        focus: 'series'
      },
      data: ${dateType == 0 ? legendData : legendData[0]}
    }
    $series2
  ]
}
 ''');
  }

  Widget _getTitle(String title) {
    return Container(
        color: Constant.appbarColor,
        padding: EdgeInsets.fromLTRB(16, 46, 16, 16),
        child: FractionallySizedBox(
          widthFactor: 1,
          child: Stack(
            alignment: Alignment.center,
            children: [
              Positioned(
                left: 2,
                top: 5,
                child: GestureDetector(
                    behavior: HitTestBehavior.translucent,
                    onTap: () {
                      Navigator.pop(context,true);
                    },
                    child: Container(
                        child: Icon(Icons.arrow_back_ios),
                        padding: EdgeInsets.fromLTRB(15, 0, 20, 10))),
              ),
              Text(title,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      fontSize: 22,
                      color: Colors.black87,
                      fontWeight: FontWeight.normal))
            ],
          ),
        ));
  }
}
